﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace TransDepot.Presentation.Web.Extensions
{
    /// <summary>
    /// Action filter that foce the conversion of one strong model to a model
    /// </summary>
    public class ForceModelParse : ActionFilterAttribute
    {
        private Type entityType;

        /// <summary>
        /// Initializes a new instance of the <see cref="ForceModelParse"/> class.
        /// </summary>
        /// <param name="EntityType">Type of the entity.</param>
        public ForceModelParse(Type EntityType)
        {
            this.entityType = EntityType;
        }

        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string jsonStr = null;

            if (filterContext.HttpContext.Request.RequestType == "POST")
                jsonStr = filterContext.HttpContext.Request.Form[0];
            else
                jsonStr = filterContext.HttpContext.Request.Params[0];

            if (!string.IsNullOrEmpty(jsonStr))
            {
                var serializer = new JavaScriptSerializer();
                jsonStr = jsonStr.Replace("/", "\\/");
                dynamic model = serializer.Deserialize(jsonStr, this.entityType);
                filterContext.ActionParameters["model"] = model;
            }
        }
    }

}